03. Function Declaration Syntax

Function Declaration Syntax

Question:

As you've learned in this course, there are two syntaxes to declare functions

var functionName = function() {}

and

function functionName() {}

The JavaScript interpreter, which is responsible for taking the code you write and preparing it to become machine code, will handle the two function declarations slightly differently because of the way it handles variable declarations.

All variable declarations will immediately get moved to the top of their scope. For example:

var x = 5;
console.log(x); // 5
var y = 10;

is the same as

var x, y; // this line simply declares x and y at the same time.
x = 5;
console.log(x); // 5
y = 10;

Notice how the declaration of y moved to the top of the scope. And also notice how the first line doesn't set a value for neither x nor y. After var x, y; both x and y are undefined.

The same behavior holds true for other types of variables, including functions. If you use the var functionName syntax, only the function's declaration (e.g. var functionName;) gets moved at the top of its scope. However, if you use function functionName() syntax, the function declaration and definition (the actual instructions inside the function) get moved to the top of the function's scope.

Your Challenge

In the following example you'll see two snippets of code. In one snippet, you'll see the var functionName syntax, while in the other you'll see function functionName(). See if you can predict which code snippet will work and which will fail.

Start Quiz:

Solution:

Example 1

example1();
function example1() {
    console.log("Ran the example");
}

You should see "Ran the example!" when you run this code.

Example 2

example2();
var example2 = function() {
    console.log("Ran the example");
}

You should see an undefined error when this code gets run.

In both examples, the interpreter modifies the code. This is effectively how this code is interpreted.

Example 1 Interpreted

var example1;
example1 = function() {
    console.log("Ran the example");
}
example1();

Example 2 Interpreted

var example2;
example2();
example2 = function() {
    console.log("Ran the example");
}

In both examples, the declarations get moved to the top of the scope. But notice how the definition comes along too in the first example, which allows us to use example1() right away.

INSTRUCTOR NOTE:

Follow your instructors!

@cwpittman

+jameswilliams

Try the code out yourself! Here it is for you to copy/paste into your browser's console.

Example 1

example1();
function example1() {
    console.log("Ran the example");
}

Example 2

example2();
var example2 = function() {
    console.log("Ran the example");
}